package com.googlecode.garbagecan.commons.execstudy;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class Sample1 {

	private static Logger logger = Logger.getLogger(Sample1.class.getName());

	public static void main(String[] args) {
		testWithCorrectCommand();
		testWithIncorrectCommand();
	}

	public static void testWithCorrectCommand() {
		//CommandLine cmdLine = CommandLine.parse("ls -l");
		
		CommandLine cmdLine = new CommandLine("ls");
		cmdLine.addArgument("-l");
		
		DefaultExecutor executor = new DefaultExecutor();
		try {
			int exitValue = executor.execute(cmdLine);
			logger.log(Level.INFO, "Exit Value: " + exitValue);
		} catch (ExecuteException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		}
	}
	
	public static void testWithIncorrectCommand() {
		CommandLine cmdLine = CommandLine.parse("thisisincorrectcommand");
		DefaultExecutor executor = new DefaultExecutor();
		try {
			int exitValue = executor.execute(cmdLine);
			logger.log(Level.INFO, "Exit Value: " + exitValue);
		} catch (ExecuteException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		}
	}
}
